//
//  RunCatApp.swift
//  RunCat
//
//  Created by wdhcr on 2023/2/20.
//

import SwiftUI

@main
struct RunCatApp: App {
    
    
    @NSApplicationDelegateAdaptor(AppDelegate.self) var appDelegate
    var body: some Scene {
        Settings {
            EmptyView()
        }
    }
}

import AppKit
class AppDelegate: NSObject, NSApplicationDelegate {
    var statusBarItem:NSStatusItem?
    
    let subMenu = NSMenu()
    
    
    @AppStorage("CurrentIconIndex") private var currentIconIndex = 0
    
    @objc func exitApp() {
        NSApplication.shared.terminate(nil)
        NSApp.terminate(nil)
    }
    
    @IBAction private func switchIcon(_ item: NSMenuItem) {
        subMenu.items.forEach{nsItem in
            nsItem.state = (nsItem.tag == item.tag) ? .on:.off
        }
        currentIconIndex = item.tag
    }
    
    func applicationDidFinishLaunching(_ notification: Notification) {
        let menu = NSMenu()
        let item1 = NSMenuItem(title: "更换图标", action:nil, keyEquivalent: "")
        menu.addItem(item1)
        menu.addItem(NSMenuItem.separator())
        menu.addItem(NSMenuItem(title: "退出", action: #selector(exitApp), keyEquivalent: ""))
        
        
        for item in imagesObj {
          let menuItem =  NSMenuItem(title: item.desp, action:#selector(switchIcon), keyEquivalent: "")
            menuItem.tag = item.id
            menuItem.state = ((item.id == currentIconIndex) ? NSControl.StateValue.on : NSControl.StateValue.off)
            subMenu.addItem(menuItem)
            
        }
        
        item1.submenu = subMenu
        
        let contentView = StatusBar(width: 22, height: 22)
        let mainView = NSHostingView(rootView: contentView)
        mainView.frame = NSRect(x: 0, y: 0, width: 22, height: 22)
        statusBarItem = NSStatusBar.system.statusItem(withLength: NSStatusItem.variableLength)
        statusBarItem?.menu = menu
        statusBarItem?.button?.title = " "
        statusBarItem?.button?.addSubview(mainView)
    }
}
